package com.community.controller;

import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.community.dto.PayDto;
import com.community.dto.StorageGatherDto;
import com.community.dto.StoragePayDto;
import com.community.pojo.*;
import com.community.pojo.Pay;
import com.community.pojo.Pay;
import com.community.service.*;
import com.community.utils.NumberUtils;
import com.community.utils.PageUtils;
import com.community.vo.GatherVo;
import com.community.vo.PayVo;
import com.community.vo.StorageGatherTwoVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author TangHaoSong Fly ChenJie HeYuHang
 * @since 2024-05-15
 */
@CrossOrigin
@Controller
@RequestMapping("/community/pay")
public class PayController {

    @Autowired
    private IOrdersService ordersService;

    @Autowired
    private IOrderDetailsService orderDetailsService;

    @Autowired
    private IPayService payService;

    @Autowired
    private IPayDetailsService payDetailsService;

    @Autowired
    private NumberUtils numberUtils;

    @Autowired
    private IStockService stockService;

    /**
     * 入库申请登记  生成出库单
     * @param dto
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public String add(@RequestBody StoragePayDto dto) {
        // 生成入库设计单编号
        int typeNumber = Integer.parseInt(numberUtils.getTypeNumber("400"));
        dto.setPayId(typeNumber);
        dto.setCheckTag("S001-3");
        BigDecimal num = new BigDecimal(0);
        dto.setTotalAmount(num);
        payService.page1(dto);
        return "ok";
    }
    /**
     * 出库单表查询
     */
    @RequestMapping("/payList")
    @ResponseBody
    public List<Pay> payList() {
        List<Pay> list = payService.list();
        return list;
    }
    /**
     * 出库单表查询
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/show/{currentPage}/{pageSize}")
    public PageUtils<Pay> show(@PathVariable int currentPage,
                                  @PathVariable  int pageSize) {
        QueryWrapper<Pay> qw = new QueryWrapper<Pay>();
        qw.eq("CHECK_TAG", "S001-1");
        PageHelper.startPage(currentPage, pageSize);
        List<Pay> list = payService.list(qw);
        PageInfo<Pay> p = new PageInfo<Pay>(list);
        PageUtils<Pay> utils = new PageUtils<Pay>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 出库单审核
     * @param vo
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/showtongguo/{currentPage}/{pageSize}")
    public PageUtils<Pay> showtongguo(@RequestBody PayVo vo, @PathVariable int currentPage, @PathVariable int pageSize) {
        QueryWrapper<Pay> qw = new QueryWrapper<Pay>();
        if (vo != null) {
            if (!StringUtils.isEmpty(vo.getSearch_payId())) {
                qw.eq("pay_id", vo.getSearch_payId());
            }
            if (!StringUtils.isEmpty(vo.getSearch_payer())) {
                qw.like("payer", vo.getSearch_payer());
            }
            if (!StringUtils.isEmpty(vo.getSearch_register())) {
                qw.like("register", vo.getSearch_register());
            }
            if (!StringUtils.isEmpty(vo.getSearch_checkTime1())) {
                qw.ge("check_time", vo.getSearch_checkTime1());
            }
            if (!StringUtils.isEmpty(vo.getSearch_checkTime2())) {
                qw.le("check_time", vo.getSearch_checkTime2());
            }
        }
        qw.eq("CHECK_TAG", "S001-1");

        PageHelper.startPage(currentPage, pageSize);
        List<Pay> list = payService.list(qw);
        PageInfo<Pay> p = new PageInfo<Pay>(list);
        PageUtils<Pay> utils = new PageUtils<Pay>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 修改仓单
     * @param
     * @return
     */
//    @RequestMapping("/updateById")
//    @ResponseBody
//    public String updateById(@RequestBody Pay pay) {
//        boolean b = payService.updateById(pay);
//        if(b){
//            return "ok";
//        }
//        return "error";
//    }
    @RequestMapping("/updateById")
    @ResponseBody
    public String updateById(int id) {
//        System.out.println(id);
        Orders orders = this.ordersService.getById(id);
        //将采购单入库标志改为已收货,配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        //配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        orders.setConveyTag("P001-3");
        ordersService.updateById(orders);
        return "ok";
    }
    /**
     * 审核通过
     * @param pay
     * @return
     */
    @ResponseBody
    @RequestMapping("/update3/{currentPage}/{pageSize}")
    public boolean update3(@RequestBody Pay pay) {
        if (pay.getCheckTag() == null) {
            // 如果 checkTag 为 null，则设置为 "S001-1"
            pay.setCheckTag("S001-1");
        }
        boolean b = payService.updateById(pay);
        return b;
    }
    /**
     * 删除
     * @param payId
     * @returnID
     */
    @ResponseBody
    @RequestMapping("/del")
    public boolean del(int payId) {
        boolean b = payService.removeById(payId);
        return b;
    }
    /**
     * 已审核,已登记
     * @param vo
     * @param currentPage
     * @param pageSize
     * @return
     */
    @RequestMapping("/twoShow2/{currentPage}/{pageSize}")
    @ResponseBody
    public PageUtils<Pay> twoShow2(StorageGatherTwoVo vo, @PathVariable int currentPage, @PathVariable int pageSize) {
        PageUtils<Pay> show = payService.twoShow(vo, currentPage, pageSize);
        return show;
    }
    /**
     * 根据id查询所有出库的
     * @param payId
     * @return
     */
    @RequestMapping("/showById")
    @ResponseBody
    public Pay showById(Integer payId) {
        Pay byId = payService.getById(payId);
        return byId;
    }
    /**
     * 入库调库表格里面的数据
     * @param
     * @return
     */
    @RequestMapping("/payById")
    @ResponseBody
    public List<PayDetails> gatherById(int id) {
        QueryWrapper<PayDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("pay_id",id);
        List<PayDetails> list = this.payDetailsService.list(wrapper);
        System.out.println("kk++++"+list);
        return list;
    }
    /**
     * 入库调库表格里面的数据
     * @param payId
     * @return
     */
    @RequestMapping("/gatherDetailsById")
    @ResponseBody
    public PageUtils<PayDetails> GatherDetailsById(Integer payId) {
        QueryWrapper<PayDetails> qw = new QueryWrapper<>();
        // 将查询条件上的左引号放置在参数名后面
        qw.eq("pay_id", payId);
        List<PayDetails> list = payDetailsService.list(qw);
        PageInfo<PayDetails> p = new PageInfo<>(list);
        PageUtils<PayDetails> utils = new PageUtils<>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 出库调度
     * @param stockId
     * @param totalAmount
     * @return
     */
    @RequestMapping("/updateTWO2")
    @ResponseBody
    public boolean updateTWO2(Integer stockId, Integer totalAmount) {
        PayDetails s = new PayDetails();
        s.setId(stockId);
        BigDecimal b = BigDecimal.ZERO; // 默认值为0
        if (totalAmount != null) {
            b = BigDecimal.valueOf(totalAmount);
        }
        s.setAmount(b);
        boolean result = payDetailsService.updateById(s);
        return result;
    }
    /**
     * 出库单表查询  根据订单查询  商户作为条件
     * @param currentPage
     * @param pageSize
     * @return
     */
    @ResponseBody
    @RequestMapping("/show2/{currentPage}/{pageSize}")
    public PageUtils<Orders> show2(@PathVariable int currentPage,
                               @PathVariable  int pageSize) {
        QueryWrapper<Orders> qw = new QueryWrapper<Orders>();
        //支付标志，K002-1（等待支付）、K002-2（支付失败）、K002-3（支付成功）
        qw.eq("pay_tag","K002-1");
        //配送标志，P001-1（待发货）、P001-2（待收货）、P001-3（已收货）
        qw.eq("convey_tag", "P001-2");
        PageHelper.startPage(currentPage, pageSize);
        List<Orders> list = ordersService.list(qw);
        PageInfo<Orders> p = new PageInfo<Orders>(list);
        PageUtils<Orders> utils = new PageUtils<Orders>();
        utils.setTotal(p.getTotal());
        utils.setRows(p.getList());
        return utils;
    }
    /**
     * 制定出库单表格里面的数据
     * @param
     * @return
     */
    @RequestMapping("/OrderById")
    @ResponseBody
    public List<OrderDetails> PurchaseOrderById(int id) {
        QueryWrapper<OrderDetails> wrapper = new QueryWrapper<>();
        wrapper.eq("orders_id",id);
        List<OrderDetails> list = this.orderDetailsService.list(wrapper);
        return list;
    }
    /**
     * 根据id查询所有订单
     * @param orderId
     * @return
     */
    @RequestMapping("/showById2")
    @ResponseBody
    public Orders showById2(Integer orderId) {
        Orders byId = ordersService.getById(orderId);
        return byId;
    }

    /**
     * 出库调度
     * @param payDto
     * @return
     */
    @RequestMapping("/add2")
    @ResponseBody
    public String add2(@RequestBody PayDto payDto) {
        System.out.println("payDto++++"+payDto);
        //制定入库单
        Pay pay1 = new Pay();
        // 生成入库设计单编号
        String typeNumberStr = numberUtils.getTypeNumber("400");
        pay1.setPayOrderNumber(typeNumberStr);
        //入库id
        pay1.setPayId(null);
        //设置审核标准:S001-1 等待审核
        pay1.setCheckTag("S001-1");
        //设置总数量
        BigDecimal num = new BigDecimal(0);
        num = payDto.getPay().getTotalAmount();
        pay1.setTotalAmount(num);
        //总价格
        pay1.setTotalPrice(payDto.getPay().getTotalPrice());
        //入库人
        pay1.setPayer(payDto.getPay().getPayer());
        // 入库理由
        pay1.setReason(payDto.getPay().getReason());
        // 入库理由
        pay1.setCheckReason(payDto.getPay().getCheckReason());
        // 审核人
        pay1.setChecker(payDto.getPay().getChecker());
        // 审核时间
        pay1.setCheckTime(new Date());
        //采购id
//        pay1.setPurchaseId(payDto.getPay().getPurchaseId());
        //添加入库单
        payService.save(pay1);
        int payId = pay1.getPayId();
//        int supplierId = payDto.getPay().getSupplierId();
        List<OrderDetails> details = payDto.getDetails();
        for (int i = 0;i<details.size();i++){
            PayDetails payDetails = new PayDetails();
            //入库明细id
            payDetails.setId(null);
            //入库单id
            payDetails.setPayId(payId);
            //商品id
            payDetails.setProductId(details.get(i).getProductId());
            //供应商id
//            payDetails.setSupplierId(supplierId);
            //数量
            payDetails.setAmount(new BigDecimal(details.get(i).getAmount()) );
            //单价
            payDetails.setPrice(new Double(details.get(i).getPrice()));
            //小计
            payDetails.setSubTotal(new Double(details.get(i).getSubtotal()));

            payDetailsService.save(payDetails);
        }
        return "ok";
    }

    /**
     * 出库调库
     * @param stock
     * @return
     */
    @RequestMapping("/update")
    @ResponseBody
    public String update(@RequestBody Stock stock) {
        System.out.println("stock++++"+stock);

        // 获取当前库存对象
        Stock currentStock = stockService.getById(stock.getStockId());
        int currentAmount = currentStock.getAmount();
        int increaseAmount = stock.getAmount();
        int newAmount = currentAmount - increaseAmount;

        // 更新库存对象
        currentStock.setAmount(newAmount);
        stockService.updateById(currentStock);
        return "ok";
    }
}
